/*******************************************************************************
 * Copyright (c) 2010 Eugene Vorobkalo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Eugene Vorobkalo - initial API and implementation
 *     Andrey Fedorov - DocActivity: 2-tabbed Document Form
 ******************************************************************************/
package org.droidpres.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;
import android.view.*;
import android.widget.*;
import org.droidpres.R;
import org.droidpres.adapter.DocProductListAdapter;
import org.droidpres.db.DB;
import org.droidpres.db.QueryHelper;
import org.droidpres.db.SpinnerDB;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.TabHost.OnTabChangeListener;
import org.droidpres.dialog.ClientInfoDialog;
import org.droidpres.utils.Const;
import org.droidpres.utils.MenuItemInfo;

public class DocActivity extends AbsListActivity {

    private static final int A_RESULT_CLIENT = 100;
    private static final int A_RESULT_PRODUCT = 101;
    private static final int A_RESULT_QTY = 102;
    private static final int A_RESULT_PRICE = 103;

    private static final int MENU_EDIT_QTY				= Menu.FIRST;
    private static final int MENU_EDIT_PRICE			= Menu.FIRST + 1;
    private static final int MENU_DELETE				= Menu.FIRST + 2;
    //private Bundle mActivityExtras;

    private CheckBox CheckPrepareToSend;
    private TextView mTvDocumentTotal;

    private ArrayList<SpinnerDB> items_prices;
    private Spinner spPriceDoc;
    private ArrayList<SpinnerDB> items_doctypes;
    private Spinner spTypeDoc;
    private ArrayList<SpinnerDB> items_firms;
    private Spinner spFirm;

    private boolean bDocChanged;
    private int mState_of_doc;
    private long mDocID;
    private String mDocClientName;

    private String mClientUID = "";
    private String mPriceUID = "";

    private DecimalFormat cf;

    final String LOG_TAG = "DocActivity";

    public DocActivity() {
        super(R.layout.doc_form, DB.TABLE_DOCUMENT_DET,
                new String[]{""},
                "",
                true
        );
    }

	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDataBase = DB.get().getWritableDatabase();
        mDocID = 0;
        Cursor newcursor;
        cf = SetupRootActivity.getCurrencyFormat(this);

        Bundle ActivityExtras;
        if( (ActivityExtras = getIntent().getExtras()) != null ){
            mDocID = ActivityExtras.getLong(Const.EXTRA_DOC_ID, 0);
            if(mDocID == 0){

                newcursor = mDataBase.rawQuery("SELECT _id FROM " + DB.TABLE_DOCUMENT + " WHERE number = 0", null);
                if (newcursor.moveToFirst()) {
                    mDocID = newcursor.getInt(0);
                    mDataBase.execSQL("UPDATE "+DB.TABLE_DOCUMENT+" SET CREATED_TIME=DATETIME('now', 'localtime') WHERE _id="+ mDocID);
                }else{
                    ContentValues cval = new ContentValues();
                    cval.put("presventype",	0);
                    cval.put("number",0);
                    cval.put("itemcount", 	0);
                    cval.put("doctype_id",	0);

                    mDocID = mDataBase.insert(DB.TABLE_DOCUMENT, null, cval);
                }
                newcursor.close();
            }
        }else if(savedInstanceState != null) {
            // No intent is available =( trying getting data from savedInstance
            bDocChanged = savedInstanceState.getBoolean("doc_changed");
            mDocID = savedInstanceState.getLong("doc_id");
            mState_of_doc = savedInstanceState.getInt("doc_state");
            mDocClientName = savedInstanceState.getString("client_name");
            mClientUID = savedInstanceState.getString("client_uid");
            mPriceUID = savedInstanceState.getString("price_uid");
        }

        int typedocid = 0; int firmid = 0; int priceid = 0;
        //String FirmUID = "";
        newcursor = mDataBase.rawQuery(
                "SELECT CREATED_TIME,docstate,client_uid,pricelist_uid,doctype_id,description,Tplists._id,Tfirms._id"+
                        " FROM " + DB.TABLE_DOCUMENT + " AS TDoc" +
                        " LEFT JOIN " + DB.TABLE_PRICELISTS + " AS Tplists ON (Tplists.uid = TDoc.pricelist_uid) "+
                        " LEFT JOIN " + DB.TABLE_FIRMS + " AS Tfirms ON (Tfirms.uid = TDoc.firm_uid) "+
                        " WHERE TDoc._id="+ mDocID, null);
        if (newcursor.moveToFirst()) {
            UpdateDocForm(newcursor.getString(0));
            mState_of_doc = newcursor.getInt(1);
            mClientUID = newcursor.getString(2);
            mPriceUID = newcursor.getString(3);
            typedocid = newcursor.getInt(4);
            //FirmUID = newcursor.getString(5);
            ((EditText) findViewById(R.id.eDocDescription)).setText(newcursor.getString(5));

            if(!newcursor.isNull(6)) priceid = newcursor.getInt(6);
            if(!newcursor.isNull(7)) firmid = newcursor.getInt(7);
        }
        newcursor.close();

        FillSpinners(priceid,typedocid,firmid);

        /*
        if (mPriceUID.length() != 0){
            newcursor = mDataBase.rawQuery("SELECT _id FROM " + DB.TABLE_PRICELISTS + " WHERE uid='"+mPriceUID+"'", null);
            if (newcursor.moveToFirst()) priceid = newcursor.getInt(0);
            newcursor.close();
        }
        if (FirmUID.length() != 0){
            newcursor = mDataBase.rawQuery("SELECT _id FROM " + DB.TABLE_FIRMS + " WHERE uid='"+FirmUID+"'", null);
            if (newcursor.moveToFirst()) firmid = newcursor.getInt(0);
            newcursor.close();
        }    */

        // AbsListActivity CODE
        Cursor cursor = createCursor();
        if (cursor != null) {
            startManagingCursor(cursor);
        }
        mAdapter = createAdapter(cursor);
        setListAdapter(mAdapter);
        registerForContextMenu(getListView());
        // AbsListActivity CODE

        CheckPrepareToSend = (CheckBox) findViewById(R.id.checkBox);

        ///////// TABS ////////////////////////////////////////////////
		TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
		tabHost.setup();

        TabHost.TabSpec tabSpec;
        
        tabSpec = tabHost.newTabSpec("taghead");
        View tabviewhead = createTabView(tabHost.getContext(), getString(R.string.tab_lbl_dochead));
        tabSpec.setIndicator(tabviewhead);
        tabSpec.setContent(R.id.tab1);
        tabHost.addTab(tabSpec);

        tabSpec = tabHost.newTabSpec("tagprod");
        View tabviewprod = createTabView(tabHost.getContext(), getString(R.string.tab_lbl_docprodlist));
        tabSpec.setIndicator(tabviewprod);
        tabSpec.setContent(R.id.tab2);
        tabHost.addTab(tabSpec);

        mTvDocumentTotal = (TextView) findViewById(R.id.tvDocumentTotal);

        SetClientAndPrice(mClientUID, true);
        UpdateDocForm(true);

	    tabHost.setOnTabChangedListener
	    	(new OnTabChangeListener() {
                public void onTabChanged(String tabId) {

                 }
	    	}
	    	);

	}

    private boolean FillSpinners(int priceid, int typedocid, int firmid) {
        boolean method_result = true;
        Cursor cursor;
        Log.d(LOG_TAG,"priceid = "+priceid);
        Log.d(LOG_TAG,"typedocid = "+typedocid);
        Log.d(LOG_TAG,"firmid = "+firmid);

        items_prices = new ArrayList<SpinnerDB>();
        ArrayAdapter<SpinnerDB> adapter_prices = new ArrayAdapter<SpinnerDB>(this,
                android.R.layout.simple_spinner_item, items_prices);
        adapter_prices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cursor = mDataBase.query(DB.TABLE_PRICELISTS,
                new String[] {"_id","name"}, null, null, null, null, null);
        items_prices.add(new SpinnerDB(0, "/ Не задан /"));
        if (cursor.moveToFirst())
            do {
                items_prices.add(new SpinnerDB(cursor.getInt(0), cursor.getString(1)));
            } while (cursor.moveToNext());
        cursor.close();

        items_doctypes = new ArrayList<SpinnerDB>();
        ArrayAdapter<SpinnerDB> adapter_doctypes = new ArrayAdapter<SpinnerDB>(this,
                android.R.layout.simple_spinner_item, items_doctypes);
        adapter_doctypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cursor = mDataBase.query(DB.TABLE_TYPEDOC,
                new String[] {"_id","name"}, null, null, null, null, null);
        items_doctypes.add(new SpinnerDB(0, "/ Не выбран /"));
        if (cursor.moveToFirst())
            do {
                items_doctypes.add(new SpinnerDB(cursor.getInt(0), cursor.getString(1)));
            } while (cursor.moveToNext());
        cursor.close();

        items_firms = new ArrayList<SpinnerDB>();
        ArrayAdapter<SpinnerDB> adapter_firms = new ArrayAdapter<SpinnerDB>(this,
                android.R.layout.simple_spinner_item, items_firms);
        adapter_firms.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cursor = mDataBase.query(DB.TABLE_FIRMS,
                new String[] {"_id","name"}, null, null, null, null, null);
        items_firms.add(new SpinnerDB(0, "/ Не выбрана /"));
        if (cursor.moveToFirst())
            do {
                items_firms.add(new SpinnerDB(cursor.getInt(0), cursor.getString(1)));
            } while (cursor.moveToNext());
        cursor.close();


        spPriceDoc = (Spinner) findViewById(R.id.spDocPrice);
        spPriceDoc.setAdapter(adapter_prices);
        spPriceDoc.getSelectedItemPosition();
        spPriceDoc.setEnabled(false); // TODO: make preferences: fixed or dynamic price
        spPriceDoc.setSelection(0);
        for (int i = 0; i < items_prices.size(); i++) {
            if (items_prices.get(i).id == priceid ) {
                spPriceDoc.setSelection(i);
                break;
            }
        }

        spTypeDoc = (Spinner) findViewById(R.id.spDocType);
        spTypeDoc.setAdapter(adapter_doctypes);
        spTypeDoc.getSelectedItemPosition();
        for (int i = 0; i < items_doctypes.size(); i++) {
            if (items_doctypes.get(i).id == typedocid ) {
                spTypeDoc.setSelection(i);
                break;
            }
        }

        spFirm = (Spinner) findViewById(R.id.spDocFirm);
        spFirm.setAdapter(adapter_firms);
        spFirm.getSelectedItemPosition();
        for (int i = 0; i < items_firms.size(); i++) {
            if (items_firms.get(i).id == firmid ) {
                spFirm.setSelection(i);
                break;
            }
        }

        return method_result;
    }

    @Override
    public void onBackPressed(){
        Log.w(LOG_TAG,"onBackPressed()");

        TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
        if(tabHost.getCurrentTab()==1) tabHost.setCurrentTab(0);
        else {
            SaveDocument();
            finish();
        }
    }
    private void UpdateSaveButton() {
        ((ImageButton) findViewById(R.id.imageButtonSave)).setClickable(
            (mState_of_doc == Const.DOCSTATE_SEND)? false : mClientUID.length()!=0
        );
    }
    private void UpdateCheckSend() {
        if(mState_of_doc != Const.DOCSTATE_SEND){
            CheckPrepareToSend.setChecked(mState_of_doc == Const.DOCSTATE_PREPARE_SEND);
        }else{
            if(CheckPrepareToSend.isClickable()){
                CheckPrepareToSend.setText(R.string.lb_doc_chkbox_send);
                CheckPrepareToSend.setChecked(true);
                CheckPrepareToSend.setClickable(false);
            }
        }
    }
    private void UpdateDocForm(boolean FirstInit) {
        if(FirstInit){
            if(mState_of_doc == Const.DOCSTATE_SEND){

                EditText formDocDescription = (EditText)findViewById(R.id.eDocDescription);
                formDocDescription.setClickable(false);
                formDocDescription.setEnabled(false);

                spPriceDoc.setEnabled(false);
                spFirm.setEnabled(false);
                spTypeDoc.setEnabled(false);
            }
        }
        getDocTotal();

        long docLines = getDocLinesCount();

        final TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
        final TabWidget tabWidget = tabHost.getTabWidget();
        final ViewGroup tab = (ViewGroup) tabWidget.getChildAt(1);
        final TextView tv = (TextView) tab.findViewById(R.id.tabsText);

        tv.setText(getString(R.string.tab_lbl_docprodlist)+((docLines>0)?"("+docLines+")":""));

        setTitle(getString(R.string.tab_lbl_orderN)+ mDocID+" "+ mDocClientName);

        UpdateSaveButton();
        UpdateCheckSend();
    }
    private void UpdateDocForm(String DocDateTime){
        // Set Date & Time on Form
        char[] CharArrayDateTime = DocDateTime.toCharArray();
        ((TextView) findViewById(R.id.textDate)).setText(CharArrayDateTime,0,10);
        ((TextView) findViewById(R.id.textTime)).setText(CharArrayDateTime,11,8);
    }
    @Override
    protected List<MenuItemInfo> createContextMenus(int position, long id) {
        List<MenuItemInfo> menus = new LinkedList<MenuItemInfo>();
        if(mState_of_doc != Const.DOCSTATE_SEND){
            menus.add(new MenuItemInfo(MENU_EDIT_QTY, R.string.lb_edit_qty));
            menus.add(new MenuItemInfo(MENU_EDIT_PRICE, R.string.lb_edit_price));
            menus.add(new MenuItemInfo(MENU_DELETE, R.string.lb_delete));
        }else return null;
        return menus;
    }
    @Override
    protected String getContextMenuTitle(int position, long id) {
        Cursor cursor = getCursor();
        cursor.moveToPosition(position);

        return QueryHelper.fieldByNameString(cursor, "prod_name");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        super.onContextItemSelected(item);

        if(mState_of_doc == Const.DOCSTATE_SEND) return true;

        AdapterView.AdapterContextMenuInfo mi = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Cursor cur;
        Intent intent;
        switch (item.getItemId()) {
            case MENU_EDIT_QTY:

                cur = getCursor();
                cur.moveToPosition(mi.position);
                intent = new Intent(this, InputQtyActivity.class);
                //Log.d("DocA_onContextItemSelected",QueryHelper.fieldByNameString(cur, "prod_name")+" 1-"+
                //        mi.id+" 2-"+
                //        QueryHelper.fieldByNameFloat(cur, "prod_price")+" 3-"+
                //        QueryHelper.fieldByNameFloat(cur, "prod_qty"));
                intent.putExtra(Const.EXTRA_PRODUCT_NAME, QueryHelper.fieldByNameString(cur, "prod_name"));
                intent.putExtra(Const.EXTRA_PRODUCT_ID, mi.id);
                intent.putExtra(Const.EXTRA_PRICE, QueryHelper.fieldByNameFloat(cur, "prod_price"));
                intent.putExtra(Const.EXTRA_CASESIZE, QueryHelper.fieldByNameFloat(cur, "prod_casesize"));
                intent.putExtra(Const.EXTRA_QTY, QueryHelper.fieldByNameFloat(cur, "prod_qty"));

                startActivityForResult(intent, A_RESULT_QTY);

                return true;

            case MENU_EDIT_PRICE:

                cur = getCursor();
                cur.moveToPosition(mi.position);
                intent = new Intent(this, InputQtyActivity.class);

                intent.putExtra(Const.EXTRA_PRODUCT_NAME, QueryHelper.fieldByNameString(cur, "prod_name"));
                intent.putExtra(Const.EXTRA_PRODUCT_ID, mi.id);
                intent.putExtra(Const.EXTRA_PRICE, QueryHelper.fieldByNameFloat(cur, "prod_price"));
                intent.putExtra(Const.EXTRA_PRICE_STOCK, 0); // todo: transfer stock price to input form

                intent.putExtra(Const.EXTRA_CASESIZE, QueryHelper.fieldByNameFloat(cur, "prod_casesize"));
                intent.putExtra(Const.EXTRA_QTY, QueryHelper.fieldByNameFloat(cur, "prod_qty"));

                intent.putExtra(Const.EXTRA_INPUT_MODE, 1);
                intent.putExtra(Const.EXTRA_MANUAL_PRICE, QueryHelper.fieldByNameFloat(cur, "prod_price"));

                startActivityForResult(intent, A_RESULT_PRICE);

                return true;
            case MENU_DELETE:
                deleteProduct(mi.id);
                return true;
        }
        return false;
    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    }
    @Override
    protected CursorAdapter createAdapter(Cursor cursor) {
        return new DocProductListAdapter(
                this,
                R.layout.doc_product_list_item,
                cursor,
                new String[] {"prod_qty", "prod_price", "prod_name", "_id"},
                new int[] {R.id.tvDocTabQty, R.id.tvDocTabPrice, R.id.tvDocTabGoods, R.id.tvDocTabSum}
        );
    }
    @Override
    protected Cursor createCursor() {
        mQueryHelper.appendFilter("DOCID", QueryHelper.FILTER_AND, DB.TABLE_DOCUMENT_DET+".order_id = %d", mDocID);
        return mQueryHelper.CreateDocProductsCursor(mDataBase);
    }
    public void butProdInput_Click(View v){
        if(mState_of_doc == Const.DOCSTATE_SEND) return;

        if(items_prices.get(spPriceDoc.getSelectedItemPosition()).id == 0){
            Toast.makeText(getBaseContext(), "Ошибка:\n"+
                    "Не выбран прайс!", 5).show();
            return;
        }
        if(mClientUID.length() == 0){
            Toast.makeText(getBaseContext(), "Ошибка:\n"+
                    "Не выбран клиент!", 5).show();
            return;
        }

        SaveDocument();

        Bundle intent_extras = new Bundle();
        intent_extras.putString(Const.EXTRA_CLIENT_NAME, mDocClientName);
        intent_extras.putString(Const.EXTRA_CLIENT_UID, mClientUID);
        intent_extras.putString(Const.EXTRA_PRICE_UID, mPriceUID);
        intent_extras.putString(Const.EXTRA_DOC_PRICE_NAME,
                items_prices.get(spPriceDoc.getSelectedItemPosition()).title);
        intent_extras.putInt(Const.EXTRA_DOC_PRICE, getPriceID());
        intent_extras.putInt(Const.EXTRA_PROD_INPUT_ONLY, 1);
        intent_extras.putLong(Const.EXTRA_DOC_ID, mDocID);

        Intent intent_document = new Intent(this, ProductListActivity.class);
        intent_document.putExtras(intent_extras);

        startActivityForResult(intent_document, A_RESULT_PRODUCT);
    }
    public void butClientInput_Click(View v){
        if(mState_of_doc == Const.DOCSTATE_SEND) return;

        Intent intent = new Intent(this, ClientListActivity.class);
        intent.putExtra(Const.EXTRA_CHOOSE_CLIENT, 1);
        intent.putExtra(Const.EXTRA_CLIENT_UID, mClientUID);
        startActivityForResult(intent, A_RESULT_CLIENT);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) return;
        float newqty;
        switch (requestCode) {
            case A_RESULT_CLIENT:
                SetClientAndPrice(data.getStringExtra(Const.EXTRA_CLIENT_UID), false);
                UpdateDocForm(false);
                break;
            case A_RESULT_PRODUCT:
                UpdateDocForm(false);
                break;
            case A_RESULT_QTY:
                newqty = data.getFloatExtra(Const.EXTRA_QTY, 0);
                ChangeQty(  data.getLongExtra(Const.EXTRA_PRODUCT_ID, 0),
                            newqty,
                            data.getFloatExtra(Const.EXTRA_PRICE, 0));
                break;
            case A_RESULT_PRICE:
                newqty = data.getFloatExtra(Const.EXTRA_QTY, 0);
                ChangeQty(  data.getLongExtra(Const.EXTRA_PRODUCT_ID, 0),
                        newqty,
                        data.getFloatExtra(Const.EXTRA_MANUAL_PRICE, 0));
                break;
        }
    }
    private void deleteProduct(long goodsID) {
        mDataBase.delete(DB.TABLE_DOCUMENT_DET,
                "order_id=" + mDocID+" AND "+
                        "product_uid=(SELECT uid FROM "+DB.TABLE_PRODUCT+" WHERE _id="+goodsID+")", null);
        requeryCursor();
        SaveDocument();

        UpdateDocForm(false);
    }
    private void ChangeQty(long goodsID, float qty, float price) {

        if (qty > 0) {
            ContentValues cval = new ContentValues();
            cval.put("qty",	qty);
            cval.put("price",   price);

            mDataBase.update(   DB.TABLE_DOCUMENT_DET,
                                cval,
                                "order_id="+mDocID+" AND "+
                                    "product_uid=(SELECT uid FROM "+DB.TABLE_PRODUCT+" WHERE _id="+goodsID+")",
                                null);
            requeryCursor();
            SaveDocument();
        } else {
            deleteProduct(goodsID);
        }
    }
    private long getDocLinesCount(){
        long itemcount = 0;
        Cursor cursor;
        cursor = mDataBase.rawQuery("SELECT COUNT(*) FROM " + DB.TABLE_DOCUMENT_DET +
                " WHERE order_id = " + mDocID, null);
        if (cursor.moveToFirst()) {
            itemcount = cursor.getLong(0);
        }
        cursor.close();
        return itemcount;
    }
    private void SetClientAndPrice(String new_client_uid, boolean bFirstFormInit){

        Log.v(LOG_TAG,"SetClientAndPrice()=======================");
        Log.v(LOG_TAG,"_new_client_uid = "+new_client_uid);
        Log.v(LOG_TAG, (bFirstFormInit) ? "bFirstFormInit=true" : "bFirstFormInit=false");

        if(new_client_uid.length() == 0){ // new empty doc without client
            bDocChanged = false;
            mDocClientName = "";
            mPriceUID = "";
            spPriceDoc.setSelection(0);
            Log.v(LOG_TAG, "_new_client_uid.length()== 0");
            Log.v(LOG_TAG, "_mDocClientName = " + mDocClientName);
            Log.v(LOG_TAG, "_mPriceUID = " + mPriceUID);
            return;
        }
        if (!bFirstFormInit && mClientUID.equals(new_client_uid)) return; // selected client not changed

        if (!bFirstFormInit){
            Log.v(LOG_TAG, "Document data changed");
            bDocChanged = true;
        }

        String old_price_uid = mPriceUID;
        Log.v(LOG_TAG, "_Old_PriceUID = "+old_price_uid);

        String NewPriceUID = "";
        //mPriceUID = "";
        Cursor cursor;
        cursor = mDataBase.rawQuery("SELECT pricelist_uid,name FROM " + DB.TABLE_CLIENT + " WHERE uid='"+new_client_uid+"'", null);
        if (cursor.moveToFirst()) {
            NewPriceUID = cursor.getString(0);
            mDocClientName = cursor.getString(1);
        }else mDocClientName = "";
        cursor.close();
        //Log.v(LOG_TAG,"_new_PriceUID = "+mPriceUID);

        mClientUID = new_client_uid;
        EditText EdT = ((EditText) findViewById(R.id.eClient));
        if(EdT != null) EdT.setText(mDocClientName);

        SetPrice(NewPriceUID,old_price_uid,bFirstFormInit);

    }

    private void SetPrice(String SetPrice, String OldPrice, boolean bFirstFormInit) {
        Cursor cursor;

        String client_price_name = items_prices.get(spPriceDoc.getSelectedItemPosition()).title;
        Log.v(LOG_TAG, "_old_Price_name = "+client_price_name);

        mPriceUID = SetPrice;
        Log.v(LOG_TAG,"_new_PriceUID = "+mPriceUID);

        if(bFirstFormInit) return;

        int NewPriceId = 0;
        boolean bPriceFound = false;
        if(mPriceUID.length() != 0){
            cursor = mDataBase.rawQuery("SELECT _id FROM " + DB.TABLE_PRICELISTS + " WHERE uid='"+mPriceUID+"'", null);
            if (cursor.moveToFirst()) {
                bPriceFound = true;
                NewPriceId = cursor.getInt(0);
            } cursor.close();
        }

        if(bPriceFound && !mPriceUID.equals(OldPrice)){   // price changed
            client_price_name = "";

            for (int i = 0; i < items_prices.size(); i++) {
                if (items_prices.get(i).id == NewPriceId) {
                    client_price_name = items_prices.get(i).title;
                    spPriceDoc.setSelection(i);
                    break;
                }
            }
            Log.v(LOG_TAG,"_new_Price_name = "+client_price_name);

            long itemcount = getDocLinesCount();
            Log.v("LOG_TAG", "itemcount = " + itemcount);
            if(itemcount>0){
                mDataBase.beginTransaction();

                mDataBase.execSQL("CREATE TABLE TEMPDET AS" +
                        " SELECT T1.order_id as order_id, T1.qty as qty, T1.product_id as product_id, T3.price as price"+
                        " FROM " + DB.TABLE_DOCUMENT_DET + " T1"+
                        " INNER JOIN " + DB.TABLE_PRODUCT+" T2 ON" +
                        " T1.product_id = T2.uid"+
                        " LEFT JOIN " + DB.TABLE_PRICES+" T3 ON" +
                        " T2._id = T3.product_id AND T3.pricelist_id = " + NewPriceId +
                        " WHERE T1.order_id = "+mDocID);

                mDataBase.execSQL("DELETE FROM "+DB.TABLE_DOCUMENT_DET+" WHERE "+DB.TABLE_DOCUMENT_DET+".order_id="+ mDocID);
                Log.d(LOG_TAG,"Doc table cleared.");

                itemcount = 0;
                cursor = mDataBase.rawQuery("SELECT COUNT(*) FROM TEMPDET", null);
                if (cursor.moveToFirst()) {
                    itemcount = cursor.getLong(0);
                }
                if(itemcount>0){
                    mDataBase.execSQL("INSERT INTO "+DB.TABLE_DOCUMENT_DET+"(order_id,qty,product_id,price) SELECT order_id,qty,product_id,price FROM TEMPDET");
                }else{
                    Log.w(LOG_TAG,"Table TEMPDET EMPTY AFTER price changes!");
                }
                mDataBase.execSQL("DROP TABLE TEMPDET");

                if(mState_of_doc != Const.DOCSTATE_SEND){
                    mState_of_doc = Const.DOCSTATE_EDIT; // reset flag of ready to send
                }
                SaveDocument();

                mDataBase.setTransactionSuccessful();
                mDataBase.endTransaction();

                Toast.makeText(getBaseContext(), "Цены документа пересчитаны"+
                        "\nна новый прайс:" + client_price_name +
                        "\nДокумент автоматически сохранен.", 5).show();
            }
        }else if(!bPriceFound){
            //mDataBase.execSQL("UPDATE "+DB.TABLE_DOCUMENT_DET+" SET price=0 WHERE order_id="+mDocID);
            spPriceDoc.setSelection(0);
            Toast.makeText(getBaseContext(),
                    "У выбранного клиента не задан прайс!", 5).show();
        }
    }

    public void butClientInfo_Click(View v){
        if(mClientUID.length() != 0){
            ClientInfoDialog dlg = new ClientInfoDialog(this);
            dlg.show(mClientUID);
        }
    }
    public void butOk_Click(View v){
        if(mState_of_doc == Const.DOCSTATE_SEND) return;

        if(mClientUID.length() == 0) return;
        SaveDocument();

        finish();
    }
    public void butReadyToSend_Click(View v){
        if(mState_of_doc == Const.DOCSTATE_SEND) return;

        if(mState_of_doc == Const.DOCSTATE_EDIT){
            mState_of_doc = Const.DOCSTATE_PREPARE_SEND;
        }else{
            mState_of_doc = Const.DOCSTATE_EDIT;
        }
    }
    public void butExit_Click(View v){
        finish();
    }
    private int getDocTypeID() {
        return items_doctypes.get(spTypeDoc.getSelectedItemPosition()).id ;
    }
    private int getFirmID() {
        return items_firms.get(spFirm.getSelectedItemPosition()).id ;
    }
    private int getPriceID() {
        return items_prices.get(spPriceDoc.getSelectedItemPosition()).id ;
    }
    private double getDocTotal(){
        double docTotal = 0;
        if(mDocID != 0){
            Cursor cursor = mDataBase.rawQuery("SELECT SUM(qty*price) FROM " + DB.TABLE_DOCUMENT_DET +
                    " WHERE order_id = " + mDocID, null);
            if (cursor.moveToFirst()) docTotal = cursor.getDouble(0);
            cursor.close();
        }
        mTvDocumentTotal.setText(cf.format(docTotal));
        return docTotal;
    }
    private String getPriceUID(){
        String getUID = "";
        Cursor cursor = mDataBase.rawQuery("SELECT uid FROM " + DB.TABLE_PRICELISTS +
                " WHERE _id = " + getPriceID(), null);
        if (cursor.moveToFirst()) {
            if(!cursor.isNull(0))
                getUID = cursor.getString(0);
        }
        cursor.close();
        return getUID;
    }
    private String getFirmUID(){
        String getUID = "";
        Cursor cursor = mDataBase.rawQuery("SELECT uid FROM " + DB.TABLE_FIRMS +
                " WHERE _id = " + getFirmID(), null);
        if (cursor.moveToFirst()) {
            if(!cursor.isNull(0))
                getUID = cursor.getString(0);
        }
        cursor.close();
        return getUID;
    }
    private void SaveDocument() {
        Log.d(LOG_TAG,"SaveDocument() start");

        if(mState_of_doc == Const.DOCSTATE_SEND) return;
        if(mClientUID.length() == 0) return;

        Log.d(LOG_TAG,"Conditions ok, saving to sqlite..");

        ContentValues cval = new ContentValues();
        cval.put("presventype",	0);
        cval.put("client_uid",   mClientUID);
        cval.put("pricelist_uid",getPriceUID());
        cval.put("firm_uid",     getFirmUID());

        cval.put("description", ((EditText)findViewById(R.id.eDocDescription)).getText().toString().trim());
        cval.put("docstate", mState_of_doc);
        cval.put("number", mDocID);
		cval.put("doctype_id", getDocTypeID());

        cval.put("mainsumm", getDocTotal());
        cval.put("itemcount", getDocLinesCount());

        mDataBase.update(DB.TABLE_DOCUMENT, cval, QueryHelper.KEY_ID + "=" + mDocID, null);
        bDocChanged = false;
        Log.d(LOG_TAG, "SaveDocument() finished");
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //TODO:
        Log.d(LOG_TAG, "onSaveInstanceState()==================");
        if(outState != null) {
            // Writing data to restore next time
            outState.putBoolean("doc_changed", bDocChanged);
            outState.putLong("doc_id", mDocID);
            outState.putInt("doc_state", mState_of_doc);
            outState.putString("client_name", mDocClientName);
            outState.putString("client_uid", mClientUID);
            outState.putString("price_uid", mPriceUID);
        }
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        Log.d(LOG_TAG, "onRestoreInstanceState()==================");
    }
	private static View createTabView(final Context context, final String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
        TextView tv = (TextView) view.findViewById(R.id.tabsText);
        tv.setText(text);
        return view;
    }
}